<?php
namespace Common\Action;
use Common\Tqklib\user_visitor;
use Common\Model\userModel;
/**
 * 前台控制器基类
 */
class FirstendAction extends TopAction
{
    protected $visitor = null;

    public function _initialize()
    {
        parent::_initialize();
        // 网站状态
        if (! C('yh_site_status')) {
            header('Content-Type:text/html; charset=utf-8');
            exit(C('yh_closed_reason'));
        }
        $this->_init_visitor();
         	$this->_cate_mod = D('itemscate')->cache(true, 100 * 60);
        $this->cur_url= strtolower($_SERVER["REQUEST_URI"]);
        $this->assign('nav_curr', $this->cur_url);
        if(S('catetree')){
        	$catetree= S('catetree');
        }else{
        $catetree=$this->_cate_mod->where('status=1 and pid=0')->field('id,name,cateimg')->order('ordid asc,id desc')->select();
        S('catetree',$catetree);
        }
        $this->assign('catetree',$catetree);
        $this->assign('request_url',$this->cur_url);
        $this->assign('islogin',C('yh_islogin'));
        $this->assign('openinvocode',C('yh_invocode'));
        $this->assign('isfanli',C('yh_isfanli'));
  }
    /**
     * 初始化访问者
     */
    private function _init_visitor()
    {
        $this->visitor = new user_visitor();
        $this->memberinfo=$this->visitor->info;
        $this->assign('visitor', $this->memberinfo);
    }



    protected function parent_pid(){
        $pid=trim(C('yh_taobao_pid'));
        $apppid=explode('_', $pid);
        return '_'.$apppid[3];
    }
    
    protected function _wechat_login($data){
       if($data){
        $res = $this->visitor->wechatlogin($data['wx_openid']);
        return $res;

}		


}


protected function taobaodetail($id){
    	$appkey = trim(C('yh_taobao_appkey'));
    	$appsecret = trim(C('yh_taobao_appsecret'));
    	if (!empty($appkey) && !empty($appsecret) && !empty($id)) {
    		vendor('taobao.taobao');
    		$c = new \TopClient();
    		$c->appkey = $appkey;
    		$c->secretKey = $appsecret;
    		$req = new \TbkItemInfoGetRequest();
    		$req->setFields("free_shipment,ratesum,shop_dsr,is_prepay,num_iid,user_type,title,seller_id,volume,pict_url,reserve_price,zk_final_price,item_url,provcity,nick");
    		$req->setPlatform("1");
    		$req->setNumIids($id);
    		$resp = $c->execute($req);
    		$resparr = xmlToArray($resp);
    		$newitem = $resparr['results']['n_tbk_item'];
    		if($newitem) return $newitem;
		}
		
		return false;
	
}

protected function agent_pid(){
$track_val=cookie('trackid');
if(!empty($track_val)){
$track=unserialize($track_val);
$track='_'.$track['t_pid'];	
$par_pid=$this->parent_pid();
$pid=str_replace($par_pid,$track,trim(C('yh_taobao_pid')));
return $pid;

}else{
return '';
}
	
}

    /**
     * SEO设置
     */
    protected function _config_seo($seo_info = array(), $data = array())
    {
        $page_seo = array(
            'title' => C('yh_site_title'),
            'keywords' => C('yh_site_keyword'),
            'description' => C('yh_site_description')
            );
        $page_seo = array_merge($page_seo, $seo_info);
        // 开始替换
        $searchs = array(
            '{site_name}',
            '{site_title}',
            '{site_keywords}',
            '{site_description}'
            );
        $replaces = array(
            C('yh_site_name'),
            C('yh_site_title'),
            C('yh_site_keyword'),
            C('yh_site_description')
            );
        preg_match_all("/\{([a-z0-9_-]+?)\}/", implode(' ', array_values($page_seo)), $pageparams);
        if ($pageparams) {
            foreach ($pageparams[1] as $var) {
                $searchs[] = '{' . $var . '}';
                $replaces[] = $data[$var] ? strip_tags($data[$var]) : '';
            }
            // 符号
            $searchspace = array(
                '((\s*\-\s*)+)',
                '((\s*\,\s*)+)',
                '((\s*\|\s*)+)',
                '((\s*\t\s*)+)',
                '((\s*_\s*)+)'
                );
            $replacespace = array(
                '-',
                ',',
                '|',
                ' ',
                '_'
                );
            foreach ($page_seo as $key => $val) {
                $page_seo[$key] = trim(preg_replace($searchspace, $replacespace, str_replace($searchs, $replaces, $val)), ' ,-|_');
            }
        }
        $this->assign('page_seo', $page_seo);
    }

protected function invicode($uid){
$mod=new userModel();
//$code=$this->randStr($uid,6);
 $str=800;
 $newstr=$str+$uid;
 $num=sprintf("%06d", $newstr);
 $data=array(
'invocode'=>$num
);
$res=$mod->where('id='.$uid)->save($data);

if($res){
return $code;
}

	
}

protected function reinvi($uid){
$reinvi=F('reinvi_'.$uid);
$score=trim(C('yh_reinte'));
if($score>0 && $uid && false ===$reinvi){
F('reinvi_'.$uid,$uid);
$mod=new userModel();
$mod->where("id='".$uid."'")->setInc('score',$score);
M('basklistlogo')->add(array(
    'uid'=>$uid,
    'integray'=>$score,
    'remark'=>'注册送+'.$score,
    'order_sn'=>'--',
    'create_time'=>NOW_TIME,
    ));

}		
}


    /**
     * 连接用户中心
     */
    protected function _user_server()
    {
        $passport = new passport(C('yh_integrate_code'));
        return $passport;
    }

    /**
     * 前台分页统一
     */
    protected function _pager($count, $pagesize, $path = null)
    {
        $pager = new Page($count, $pagesize);
        if($path){
            $pager->path = $path;
        }
        $pager->rollPage = 3;
        $pager->setConfig('header', '条记录');
        $pager->setConfig('prev', '上一页');
        $pager->setConfig('next', '下一页');
        $pager->setConfig('first', '第一页');
        $pager->setConfig('last', '最后一页');
        $pager->setConfig('theme', '%upPage% %first% %linkPage% %end% %downPage%');
        return $pager;
    }
   
    protected function isMobile(){
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        } 
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
        { 
        // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        } 
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
                ); 
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            } 
        } 
    // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        { 
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            } 
        } 
        return false;
    } 

    
    public function _empty()
    {
        $this->display(ACTION_NAME);
    }

    
}